package com.hellogood.work.evaluate.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.hellogood.work.evaluate.client.common.CommonMessages;
import com.hellogood.work.evaluate.client.common.LoginUser;
import com.hellogood.work.evaluate.shared.po.User;
import com.hellogood.work.evaluate.shared.services.UserService;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Canvas;


public class WorkEvaluate implements EntryPoint {

	private Canvas canvas = null;

	private LoginPanel loginPanel = null;

	public void onModuleLoad() {
		loginPanel = new LoginPanel();
		loginPanel.getUserNameItem().setRequired(true);

		loginPanel.getPasswordItem().setRequired(true);

		canvas = new Canvas();
		canvas.setWidth100();
		canvas.setHeight100();
		canvas.setMargin(10);
		canvas.addChild(loginPanel);
		canvas.setAlign(Alignment.CENTER);
		canvas.draw();

		loginPanel.getLoginBtn().addClickHandler(new com.smartgwt.client.widgets.form.fields.events.ClickHandler() {

			@Override
			public void onClick(com.smartgwt.client.widgets.form.fields.events.ClickEvent event) {

				if (loginPanel.getForm().validate()) {
					Object username = loginPanel.getUserNameItem().getValue();
					Object password = loginPanel.getPasswordItem().getValue();
					if (username != null && password != null) {
						login(username.toString(), password.toString());
					} else {
						SC.say(CommonMessages.LoginInputError);
					}
				}
			}
		});
		loginPanel.getUserNameItem().focusInItem();
	}

	private void login(String username, String password) {
		UserService.Util.getInstance().login(username, password, new LoginAsyncCallback());
	}

	private class LoginAsyncCallback implements AsyncCallback<User> {

		@Override
		public void onFailure(Throwable caught) {
			SC.say(caught.getMessage());
		}

		@Override
		public void onSuccess(User result) {
			if (result == null) {
				SC.say(CommonMessages.LoginInputError);
			} else {
				LoginUser.getInstance().setCurrentUser(result);
				if (canvas.contains(loginPanel)) {
					canvas.removeChild(loginPanel);
				}
				canvas.addChild(new MainPanel());
				if (canvas.isDrawn()) {
					canvas.redraw();
				} else {
					canvas.draw();
				}
			}
		}

	}
}
